<template>
  <div class="statistics">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>热门菜品统计</span>
              <el-select v-model="selectedDays" @change="loadPopularFoods" style="width: 120px">
                <el-option label="7天" :value="7" />
                <el-option label="30天" :value="30" />
                <el-option label="90天" :value="90" />
              </el-select>
            </div>
          </template>
          
          <el-table :data="popularFoods" v-loading="loading">
            <el-table-column type="index" label="排名" width="80" />
            <el-table-column prop="name" label="菜品名称" />
            <el-table-column prop="choice_count" label="选择次数" width="120">
              <template #default="{ row }">
                <el-tag type="success">{{ row.choice_count }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="热度" width="200">
              <template #default="{ row }">
                <el-progress
                  :percentage="getPercentage(row.choice_count)"
                  :color="getProgressColor(row.choice_count)"
                  :show-text="false"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>今日选择记录</span>
          </template>
          
          <el-table :data="todayChoices" v-loading="todayLoading" max-height="400">
            <el-table-column prop="foodName" label="菜品名称" />
            <el-table-column prop="createTime" label="选择时间" width="180">
              <template #default="{ row }">
                {{ formatTime(row.createTime) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>系统概览</span>
          </template>
          
          <div class="overview-stats">
            <div class="stat-item">
              <div class="stat-value">{{ systemStats.totalCategories }}</div>
              <div class="stat-label">总分类数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ systemStats.totalFoods }}</div>
              <div class="stat-label">总菜品数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ systemStats.todayChoices }}</div>
              <div class="stat-label">今日选择</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ systemStats.enabledFoods }}</div>
              <div class="stat-label">启用菜品</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { getPopularFoods, getTodayChoices } from '../api/statistics'
import { getEnabledCategories } from '../api/category'
import { getAllEnabledFoods } from '../api/food'
import { ElMessage } from 'element-plus'

export default {
  name: 'Statistics',
  setup() {
    const popularFoods = ref([])
    const todayChoices = ref([])
    const loading = ref(false)
    const todayLoading = ref(false)
    const selectedDays = ref(7)
    const maxChoiceCount = ref(0)
    
    const systemStats = ref({
      totalCategories: 0,
      totalFoods: 0,
      todayChoices: 0,
      enabledFoods: 0
    })
    
    const loadPopularFoods = async () => {
      loading.value = true
      try {
        const res = await getPopularFoods(selectedDays.value)
        popularFoods.value = res.data
        maxChoiceCount.value = Math.max(...res.data.map(item => item.choice_count), 1)
      } catch (error) {
        ElMessage.error('加载热门菜品失败')
      } finally {
        loading.value = false
      }
    }
    
    const loadTodayChoices = async () => {
      todayLoading.value = true
      try {
        const res = await getTodayChoices()
        todayChoices.value = res.data
        systemStats.value.todayChoices = res.data.length
      } catch (error) {
        ElMessage.error('加载今日选择失败')
      } finally {
        todayLoading.value = false
      }
    }
    
    const loadSystemStats = async () => {
      try {
        // 加载分类统计
        const categoriesRes = await getEnabledCategories()
        systemStats.value.totalCategories = categoriesRes.data.length
        
        // 加载菜品统计
        const foodsRes = await getAllEnabledFoods()
        systemStats.value.totalFoods = foodsRes.data.length
        systemStats.value.enabledFoods = foodsRes.data.filter(f => f.status === 1).length
      } catch (error) {
        console.error('加载系统统计失败:', error)
      }
    }
    
    const getPercentage = (count) => {
      return Math.round((count / maxChoiceCount.value) * 100)
    }
    
    const getProgressColor = (count) => {
      const percentage = getPercentage(count)
      if (percentage >= 80) return '#67c23a'
      if (percentage >= 60) return '#e6a23c'
      if (percentage >= 40) return '#f56c6c'
      return '#909399'
    }
    
    const formatTime = (timeStr) => {
      if (!timeStr) return ''
      return new Date(timeStr).toLocaleString('zh-CN')
    }
    
    onMounted(() => {
      loadPopularFoods()
      loadTodayChoices()
      loadSystemStats()
    })
    
    return {
      popularFoods,
      todayChoices,
      loading,
      todayLoading,
      selectedDays,
      systemStats,
      loadPopularFoods,
      getPercentage,
      getProgressColor,
      formatTime
    }
  }
}
</script>

<style scoped>
.statistics {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.overview-stats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}
</style>